package com.hyts.classcode.execute;

import com.hyts.classcode.execute.config.ExecuteConfig;
import com.hyts.guava.String.Strings;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.execute
 * author:Libo/Alex
 * create-date:2019-05-28 00:11
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: 执行code java执行器
 */
public class JavaCodeExecutor implements JavaExecutor{

    /**
     * 解析input-参数-信息操作
     * @param inputParameters
     * @return
     */
    @Override
    public String[] resolveInputParameter(String inputParameters) {
        //inputParameter参数
        if(Strings.isNotBlank(inputParameters)){
            for(String param:ExecuteConfig.INPUT_PARAM_SPLIT_TOKEN){
                if(inputParameters.contains(param)){
                    return inputParameters.split(param);
                }
            }
        }
        return new String[0];
    }

    /**
     * 设置绑定当前的args参数-主线程的参数
     * @param inputParameters
     */
    @Override
    public void setInputParameter(String[] inputParameters) {
        //输入参数
        StringWriter stringWriter = new StringWriter();
        for(String inputParameter:inputParameters){
            stringWriter.append(inputParameter).append(" ");
        }
        BufferedInputStream argInputStrem = new BufferedInputStream(new ByteArrayInputStream(stringWriter.toString().getBytes()));
        System.setIn(argInputStrem);
    }

    /**
     * 执行方法操作
     * @param clazz
     * @param args
     * @return
     */
    @Override
    public String execute(Class clazz, String args) {
        setInputParameter(resolveInputParameter(args));
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream(1024);
        PrintStream cacheStream = new PrintStream(baoStream);
        PrintStream oldStream = System.out;
        //将输出结果保持到baoStream中，以便后面用
        System.setOut(cacheStream);
        //执行Main方法
        Method method = null;
        try {
            method = clazz.getMethod(ExecuteConfig.EXECUTE_MAIN_FUNCTION_NAME, String[].class);
            method.invoke(null, (Object) new String[]{});
            System.setOut(oldStream);
            //将输出打印到控制台
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return baoStream.toString();
    }

    public static void main(String[] args){

        System.out.println(System.lineSeparator());
        System.out.println(System.getenv());
        System.out.println(System.lineSeparator());

    }

}
